﻿#pragma execution_character_set("utf-8")
#include "searchfriend.h"
#include "ui_searchfriend.h"

SearchFriend::SearchFriend(HttpClient *httpClient,FileOperator* fileOperator,SQLiteUtil* sQLiteUtil,const QString &email,const QString &username,QWidget *parent) :
    QWidget(parent),
    httpClient(httpClient),
    fileOperator(fileOperator),
    sQLiteUtil(sQLiteUtil),
    email(email),
    username(username),
    ui(new Ui::SearchFriend)
{
    ui->setupUi(this);
    this->setAttribute(Qt::WA_DeleteOnClose);//窗口close后释放内存
    setAttribute(Qt::WA_DeleteOnClose);    //窗口close后释放内存
    setWindowFlags(Qt::FramelessWindowHint);    //隐藏标题栏（无边框）
    setAttribute(Qt::WA_StyledBackground);    //启用样式背景绘制
    setAttribute(Qt::WA_TranslucentBackground);    //背景透明
    setAttribute(Qt::WA_Hover);


    ui->widget_5->resize(QApplication::primaryScreen()->size());
    ui->mask_WT->hide();

    loadHttpComponentRespond();
    loadBaseComponentRespond();

    createShadow();

    //获取好友列表
    insertLabel("新的朋友",OrientType::BACK);
    {
        SearchFriendItem* item=new SearchFriendItem(ServiceType::newFriend,"新的朋友");
        connect(item,&SearchFriendItem::clicked,this,&SearchFriend::friendItemClick);
        connect(item,&SearchFriendItem::clicked,this,&SearchFriend::showApplicationList);
        insertFriendList(item,OrientType::BACK);
    }
    insertLabel("朋友",OrientType::BACK);
    loadFriendList();
    //加载本地申请信息，排序顺序由时间从大到小排序

    //获取申请列表
    httpClient->post(QString("/App/getApplication?email=%1").arg(this->email));
}

SearchFriend::~SearchFriend()
{
    delete applicationDialog;
    delete agreeApplicationDialog;
    delete ui;
}
void SearchFriend::mousePressEvent(QMouseEvent* event) {
    if (event->button() == Qt::LeftButton&&!isMaximized()) {
        isDragging = true;
        lastPos =event->pos(); // 鼠标按下时记录鼠标相对窗体的位置
    }
}
//鼠标移动事件
void SearchFriend::mouseMoveEvent(QMouseEvent* event) {
    if (isDragging&&event->buttons() & Qt::LeftButton&&!isMaximized()) {
        // 移动窗口
        move(event->globalPos() - lastPos);//event->globalPos()记录窗体的原点在整个电脑窗口的位置
    }
}

//鼠标释放事件
void SearchFriend::mouseReleaseEvent(QMouseEvent* event){
    if (event->button() == Qt::LeftButton && isDragging&&!isMaximized()) {
        isDragging = false;
    }
}

void SearchFriend::createShadow(){
    QGraphicsDropShadowEffect *mainShadow = new QGraphicsDropShadowEffect(this);
    mainShadow->setOffset(0,0); // 设置阴影偏移量
    mainShadow->setBlurRadius(13); // 设置阴影模糊半径
    mainShadow->setColor(QColor(130,130,130)); // 设置阴影颜色（RGBA）
    ui->SearchFriend_content->setGraphicsEffect(mainShadow);
}

void SearchFriend::friendItemClick(SearchFriendItem* newItem){
    static SearchFriendItem* lastItem=nullptr;
    newItem->setClickStyle();
    if (lastItem == nullptr)
        lastItem = newItem;
    else if (lastItem != newItem)
    {
        lastItem->setNormalStyle();
        lastItem = newItem;
    }
}

void SearchFriend::showApplicationList(){
    ui->show_SWT->setCurrentIndex(0);
}

void SearchFriend::showFriendInfo(const QString &email){
    ui->show_SWT->setCurrentIndex(1);
    updateHeadImg(email);
    QVariantMap resultMap=sQLiteUtil->selectOneFriendInfo(email);
    QString name;
    if(resultMap["noteName"].isNull()||resultMap["noteName"].toString().isEmpty())
        name=resultMap["userName"].toString();
    else
        name=resultMap["noteName"].toString();
    ui->username_LB->setText(name);
    ui->orginalname_LB->setText(resultMap["userName"].toString());
    ui->account_LB->setText(email);
    ui->notes_LE->setText(name);
    ui->sign_LB->setText(resultMap["sign"].toString());
}

void SearchFriend::addFriend(const QString &email,const QString &username){
    if(applicationDialog==nullptr){
        applicationDialog=new ApplicationDialog(email,this);
        applicationDialog->setText(this->username);
        applicationDialog->setNoteName(username);
        ui->mask_WT->show();
        applicationDialog->show();

        connect(applicationDialog,&ApplicationDialog::finished,this,&SearchFriend::hideMask);
        connect(applicationDialog,&ApplicationDialog::sendApplication,this,&SearchFriend::sendApplication);
    }
}

void SearchFriend::agreeFriend(const QString &email,const QString &username){
    if(agreeApplicationDialog==nullptr){
        agreeApplicationDialog=new AgreeApplicationDialog(email,this);
        agreeApplicationDialog->setNoteName(username);
        ui->mask_WT->show();
        agreeApplicationDialog->show();
        connect(agreeApplicationDialog,&AgreeApplicationDialog::finished,this,&SearchFriend::hideMask);
        //connect(applicationDialog,&ApplicationDialog::sendApplication,this,&SearchFriend::sendApplication);
    }
}

void SearchFriend::hideMask(){
    if(applicationDialog!=nullptr)
        applicationDialog=nullptr;
    if(agreeApplicationDialog!=nullptr)
        agreeApplicationDialog=nullptr;
    ui->mask_WT->hide();
}

void SearchFriend::insertLabel(const QString &text,OrientType type){
    QLabel* label=new QLabel;
    label->setText(text);
    label->setFixedHeight(20);
    label->setStyleSheet(R"(
        padding-left:15px;
        font: 9pt "Microsoft YaHei UI";
        color:rgb(153, 153, 153);
    )");
    insertFriendList(label,type);
}

void SearchFriend::insertFriendList(QWidget* widget,OrientType type){
    insertWidget((QBoxLayout*)ui->friendList_WT->layout(),widget,type);
}

void SearchFriend::insertSearchList(QWidget* widget,OrientType type){
    insertWidget((QBoxLayout*)ui->searchList_WT->layout(),widget,type);
}

void SearchFriend::insertApplicationList(QWidget* widget,OrientType type){
    insertWidget((QBoxLayout*)ui->applicationList_WT->layout(),widget,type);
}

void SearchFriend::loadFriendList(){
    if(sQLiteUtil->selectOneFriendIsExist()){
        QList<QVariantMap> list=sQLiteUtil->selectAllFriendFUsername();
        for(auto &map:list){
            QString name;
            if(map["noteName"].isNull()||map["noteName"].toString().isEmpty())
                name=map["userName"].toString();
            else
                name=map["noteName"].toString();
            SearchFriendItem* item=new SearchFriendItem(map["friendId"].toString(),name);
            insertFriendList(item,OrientType::BACK);
            map.clear();
            list.pop_front();

            connect(item,&SearchFriendItem::clicked,this,&SearchFriend::friendItemClick);
            connect(item,&SearchFriendItem::onClicked,this,&SearchFriend::showFriendInfo);
        }
    }
}

void SearchFriend::loadHttpComponentRespond(){
    connect(httpClient,&HttpClient::finished,[this](const QUrl &url, const QByteArray &data){
        QString URL=url.toString();
        if(URL.contains("get_head_img")){
            QMap<QString,QString> urlMap=this->fileOperator->getQueryParamsFromUrl(URL,"&&");
            if(!urlMap["temporary"].isNull()){
                if(urlMap["temporary"]=="0")
                    updateFriendListHImg(urlMap["email"]);
                else if(urlMap["temporary"]=="1")
                    emit showTemporaryImage(this,urlMap["email"],data);
            }
        }
        else if(URL.contains("search"))
        {
            QVariantList variantList=this->fileOperator->parseJsonArray(data);
            for(auto &it:variantList)
            {
                QVariantMap map=it.toMap();
                SearchItem* item=new SearchItem(map["email"].toString(),map["userName"].toString());
                insertSearchList(item,OrientType::BACK);

                if(this->sQLiteUtil->selectOneFriendIsExist(map["email"].toString())){
                    connect(item,&SearchItem::onClicked,this,&SearchFriend::showFriendInfo);
                    item->updateStatus();
                }
                else{
                    connect(item,&SearchItem::addFriend,this,&SearchFriend::addFriend);//显示窗口
                    connect(this,&SearchFriend::showTemporaryImage,item,&SearchItem::setTemporaryImage);
                    //获取用户的头像
                    this->httpClient->get(headImgUrl+QString("&&email=%1&&temporary=1").arg(map["email"].toString()));
                }
            }
        }
        else if(URL.contains("getApplication")){//没有将申请保存在数据库中
            QVariantList variantList=this->fileOperator->parseJsonArray(data);
            for(auto &it:variantList)
            {
                QVariantMap map=it.toMap();
                QString friendId=map["friendId"].toString();
                ApplicationItem* item=new ApplicationItem(map["friendId"].toString(),map["userName"].toString(),map["content"].toString());
                //数据显示
                insertApplicationList(item,OrientType::FRONT);
                connect(item,&ApplicationItem::agreeApplication,this,&SearchFriend::agreeApplication);
                connect(this,&SearchFriend::showTemporaryImage,item,&ApplicationItem::setTemporaryImage);
                //获取用户的临时头像
                this->httpClient->get(headImgUrl+QString("&&email=%1&&temporary=1").arg(friendId));

                //插入到数据库中
                if(!this->sQLiteUtil->selectOneApplicationIsExist(friendId))//查看原本数据库中有没有申请信息
                    this->sQLiteUtil->insertApplication(map);
                else{
                    QString buildTime=sQLiteUtil->selectOneApplicationBuildTime(friendId);
                    if(buildTime!=map["buildTime"])//判断信息是否最新的
                        this->sQLiteUtil->updateApplication(map,friendId);
                }
            }
        }
        else if(URL.contains("buildRelationship")){
            //friendId,buildTime
            QVariantMap map=this->fileOperator->parseJsonObject(data);
            SearchItem* sitem=findSearchItem(map["friendId"].toString());
            if(sitem!=nullptr)
                sitem->updateStatus();
            //更新数据的状态
        }
        else if(URL.contains("confirmRelationship")){
            //确认好友申请，获取好友的基本信息
            //friendId,userName,noteName,sign,alterTime,buildTime
            QVariantMap map=fileOperator->parseJsonObject(data);
            QString buildTime=map["buildTime"].toString();
            QString friendId=map["friendId"].toString();
            map.remove("buildTime");
            sQLiteUtil->insertFriend(map);//数据库保存好友的信息
            map.clear();
            map["status"]=1;
            map["buildTime"]=buildTime;
            sQLiteUtil->updateApplication(map,friendId);//更新申请信息状态和申请建立时间
            emit updateFriend(friendId,sQLiteUtil->selectOneApplicationContent(friendId),buildTime);//更新qqmain的好友列表项和消息项

            //更新申请项
            ApplicationItem* aitem=findApplicationItem(friendId);
            if(aitem!=nullptr)
                aitem->updateStatus();
            //更新SearchFriend的好友列表项
            updateFriendList(aitem->getEmail(),aitem->getUsername());
            //获取好友的头像
            this->httpClient->get(headImgUrl+QString("&&email=%1&&temporary=0").arg(aitem->getEmail()));
        }
    });
}

void SearchFriend::loadBaseComponentRespond(){
    connect(ui->notes_LE,&SearchLineEdit::outFocus,[this](){
        ui->notes_LE->setReadOnly(true);
        ui->notes_LE->setStyleSheet(R"(
                border:none;
                background-color:rgb(240, 240, 240);
            )");
        ui->username_LB->setText(ui->notes_LE->text());
        if(ui->notes_LE->text()!=ui->username_LB->text()){
            //更新数据库的别名
            QVariantMap map;
            map["noteName"]=ui->notes_LE->text();
            this->sQLiteUtil->updateFriendBind(map,ui->account_LB->text());
        }
    });

    connect(ui->alertNote_BT,&QPushButton::clicked,[this](){
        ui->notes_LE->setReadOnly(false);
        ui->notes_LE->setStyleSheet(R"(
            border:1px solid green;
            background-color:white;
            border-radius:5px;
        )");
        ui->notes_LE->setFocus();
    });

    connect(ui->minimize_BT,&QPushButton::clicked,[this](){
        showMinimized();
    });

    connect(ui->close_BT,&QPushButton::clicked,[this](){
        emit closeClicked();
        this->hide();
    });

    connect(ui->search_BT,&QPushButton::clicked,[this](){
        clearSearchList();
        QString text=ui->lineEdit->text();
        text.replace(QRegExp("\\s+"), "");
        if(!text.isEmpty()){
            this->httpClient->post(QString("/App/search?email=%1&&text=%2").arg(this->email).arg(ui->lineEdit->text()));
            ui->search_SWT->setCurrentIndex(1);
        }
    });

    connect(ui->lineEdit,&SearchLineEdit::onFocus,[this](){
        ui->cancel_WT->setMinimumWidth(30);
        ui->cancel_WT->setMaximumWidth(30);
        ui->widget_4->setStyleSheet(R"(
            QWidget{
                border-radius:5px;
                background-color:white;
            }
        )");
    });

    connect(ui->lineEdit,&SearchLineEdit::outFocus,[this](){
        if(ui->lineEdit->text().isEmpty()){
            clearSearchList();
            ui->lineEdit->setText("");
            ui->cancel_WT->setMinimumWidth(0);
            ui->cancel_WT->setMaximumWidth(0);
            ui->widget_4->setStyleSheet(R"(
                QWidget{
                    border-radius:5px;
                    background-color:rgb(226, 226, 226);
                }
            )");
            ui->search_SWT->setCurrentIndex(0);
        }
    });

    connect(ui->cancelSearch_BT,&QPushButton::clicked,[this](){
        clearSearchList();
        ui->lineEdit->setText("");
        ui->cancel_WT->setMinimumWidth(0);
        ui->cancel_WT->setMaximumWidth(0);
        ui->widget_4->setStyleSheet(R"(
                QWidget{
                    border-radius:5px;
                    background-color:rgb(226, 226, 226);
                }
            )");
        ui->search_SWT->setCurrentIndex(0);
    });
}

void SearchFriend::clearSearchList(){
    QVBoxLayout* SearchList=(QVBoxLayout*)ui->searchList_WT->layout();
    while(SearchList->count()>1){
        QWidget* item=SearchList->itemAt(0)->widget();
        SearchList->removeWidget(item);
        item->deleteLater();
    }
}

void SearchFriend::sendApplication(const QString &email,const QString &content,const QString &notename){
    //发送申请到服务器
    QVariantMap map;
    map["userId"]=this->email;
    map["friendId"]=email;
    map["userName"]=this->username;
    map["noteName"]=notename;
    map["content"]=content;
//    map["buildTime"]=QDateTime::currentMSecsSinceEpoch();
    this->httpClient->post("/App/buildRelationship",toJson(map));
}

void SearchFriend::agreeApplication(const QString &email,const QString &notename){
    QVariantMap map;
    map["userId"]=this->email;
    map["friendId"]=email;
    map["noteName"]=notename;
//    map["buildTime"]=QDateTime::currentMSecsSinceEpoch();
    this->httpClient->post("/App/confirmRelationship",toJson(map));
}

SearchItem* SearchFriend::findSearchItem(const QString &email){
    QVBoxLayout* layout=(QVBoxLayout*)ui->searchList_WT->layout();
    SearchItem* item=nullptr;
    for(int i=0;i<layout->count()-1;i++){
        item=(SearchItem*)layout->itemAt(i)->widget();
        if(item->getEmail()==email){
            return item;
        }
    }
    return nullptr;
}

ApplicationItem* SearchFriend::findApplicationItem(const QString &email){
    QVBoxLayout* layout=(QVBoxLayout*)ui->applicationList_WT->layout();
    ApplicationItem* item=nullptr;
    for(int i=0;i<layout->count()-1;i++){
        item=(ApplicationItem*)layout->itemAt(i)->widget();
        if(item->getEmail()==email){
            return item;
        }
    }
    return nullptr;
}
void SearchFriend::updateFriendListHImg(QString &email){
    if(email!=this->email){
        QVBoxLayout* friendList=qobject_cast<QVBoxLayout*>(ui->friendList_WT->layout());
        if(friendList->count()-4>0){
            for(int i=3;i<friendList->count()-1;i++){
                SearchFriendItem* item=qobject_cast<SearchFriendItem*>(friendList->itemAt(i)->widget());
                if(item->getEmail()==email){
                    item->updateHeadImg();
                    break;
                }
            }
        }
    }
}
void SearchFriend::updateHeadImg(const QString &email){
    if(QFile::exists(QString("./accountData/Res/%1/headImg/head.png").arg(email)))
    {
        ui->headImg_LB->setStyleSheet(QString("\
            border-radius:37px;\
            border-image:url('./accountData/Res/%1/headImg/head.png') 0 0 0 0 stretch stretch;\
        ").arg(email));
    }
}

void SearchFriend::updateFriendList(const QString &email,const QString &username){
    SearchFriendItem* fitem=new SearchFriendItem(email,username);
    connect(fitem,&SearchFriendItem::clicked,this,&SearchFriend::friendItemClick);
    connect(fitem,&SearchFriendItem::onClicked,this,&SearchFriend::showFriendInfo);
    ((QBoxLayout*)ui->friendList_WT->layout())->insertWidget(3,fitem);
}

void SearchFriend::updateApplication(const QString &email){
    ApplicationItem* item=findApplicationItem(email);
    if(item!=nullptr){
        delete item;
    }
    QVariantMap map=sQLiteUtil->selectOneApplication(email);
    item=new ApplicationItem(email,map["userName"].toString(),map["content"].toString());
    insertApplicationList(item,OrientType::FRONT);
    connect(item,&ApplicationItem::agreeApplication,this,&SearchFriend::agreeApplication);
    connect(this,&SearchFriend::showTemporaryImage,item,&ApplicationItem::setTemporaryImage);
    //获取用户的临时头像
    this->httpClient->get(headImgUrl+QString("&&email=%1&&temporary=1").arg(email));
}

QByteArray SearchFriend::toJson(QVariantMap &map){
    QJsonDocument jsonDoc(this->fileOperator->recursiveWriteJsonObject(map));
    return jsonDoc.toJson();
}
